# coding=utf-8

from common import orm
from common.utils import track_logging
from common.utils.db import list_object, get, upsert
from common.utils.decorator import sql_wrapper
from common.withdraw.model import WithdrawChannel, CHANNEL_TYPE

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def get_withdraw_channel(id):
    return get(WithdrawChannel, id)


@sql_wrapper
def upsert_withdraw_channel(info, id=None):
    return upsert(WithdrawChannel, info, id)


@sql_wrapper
def create_withdraw_channel(info, id=None):
    return upsert(WithdrawChannel, info, id)


@sql_wrapper
def list_withdraw_channel(query_dct):
    return list_object(query_dct, WithdrawChannel)


@sql_wrapper
def delete_withdraw_channel(channel_id):
    WithdrawChannel.query.filter(WithdrawChannel.id == channel_id).update({'deleted': 1})
    orm.session.commit()
    return {}


@sql_wrapper
def get_all_channels():
    resp = {}
    channels, _ = list_withdraw_channel({})
    for channel in channels:
        resp[channel.id] = channel.channel_name
    resp[CHANNEL_TYPE.MANUAL] = CHANNEL_TYPE.get_label(CHANNEL_TYPE.MANUAL)
    return resp


@sql_wrapper
def get_all_channel_type():
    resp = {}
    channels, _ = list_withdraw_channel({})
    for channel in channels:
        resp[channel.id] = channel.channel_type
    resp[CHANNEL_TYPE.MANUAL] = CHANNEL_TYPE.MANUAL
    return resp


@sql_wrapper
def get_all_channel_rate():
    sum, count = 0, 0
    channels, _ = list_withdraw_channel({})
    for channel in channels:
        sum += float(channel.rate)
        count += 1
    return sum / count


@sql_wrapper
def get_channel_rate(third_type):
    query = WithdrawChannel.query.filter(WithdrawChannel.id == third_type).first()
    return query.rate
